<template>
  <div class="container">
    <Headbar/>
    <HeadMenu pageFrom="product" :kw="kw" hasKeys="yes"/>
    <Hungbar/>
    <div :class="firstTrades?'firstTrades search-main':'search-main'">
      <div :class="secondTrades?'secondTrades search-result':'search-result'">
        <div :class="thirdTrades?'thirdTrades search-conditions':'search-conditions'">
          <el-breadcrumb separator-class="none">
            <el-breadcrumb-item style="cursor: pointer"><span @click="getAllResult()">所有结果</span></el-breadcrumb-item>
            <el-breadcrumb-item>
              <el-select v-model="first" filterable :placeholder="defaultFirst" @change="changeFirstTrade">
                <el-option
                        v-for="item in firstTrades"
                        :key="item.tradeName"
                        :label="item.tradeName"
                        :value="item.tradeId">
                </el-option>
              </el-select>
              <i v-if="secondTrades" class="el-icon-arrow-right"></i>
            </el-breadcrumb-item>
            <el-breadcrumb-item v-if="secondTrades && secondTrades.length > 0">
              <el-select v-model="second" filterable :placeholder="defaultSecond"
                         @change="changeSecondTrade">
                <el-option
                        v-for="item in secondTrades"
                        :key="item.tradeId"
                        :label="item.tradeName"
                        :value="item.tradeId">
                </el-option>
              </el-select>
              <i v-if="thirdTrades" class="el-icon-arrow-right"></i>
            </el-breadcrumb-item>
            <el-breadcrumb-item v-if="thirdTrades && thirdTrades.length > 0">
              <el-select v-model="third" filterable :placeholder="defaultThird"
                         @change="changeThirdTrade">
                <el-option
                        v-for="item in thirdTrades"
                        :key="item.tradeId"
                        :label="item.tradeName"
                        :value="item.id">
                </el-option>
              </el-select>
            </el-breadcrumb-item>
            <!--<span class="search-item">
              <input class="search-all-input" v-model="productName" type="text" placeholder="请输入" @blur="selectList">
              <span class="search-btn">
                <img src="../../assets/images/search/search_01.png"/>
              </span>
            </span>-->
            <el-tag
                    :key="idx"
                    v-for="(item, idx) in dynamicTags"
                    closable
                    :disable-transitions="false"
                    @close="handleClose(item.index, item.key)">
              {{item.value}}
            </el-tag>

            <span class="product-total">共 {{total}} 件商品</span>
          </el-breadcrumb>

        </div>
        <div :class="attributeList && attributeList.length>5?'search-classify': 'search-classify noPadding'" v-if="attributeList && attributeList.length > 0">
          <div class="search-classify-list">
            <div class="search-classify-row" v-for="(item, i) in attributeList" :key="i"
                 :class="{ 'hide' : (i>4 && hideMore) }" v-if="hiddenAttributes.indexOf(i)<0">
              <el-row>
                <el-col :span="3">
                  <div class="grid-content bg-kw grid-left">
                    {{ item.name }}
                  </div>
                </el-col>
                <el-col :span="21" class="grid-right" :class="{'more': item.open}">
                  <el-col :span="22">
                    <div class="grid-content bg-kw-light">
                      <div class="classify-kw cursor" :class="{'active': panel.active}"
                           v-for="(panel, j, index) in item.values" :key="index" @click="chooseAttribute(i, panel, j, item)">
                        <i class="checkbox" :class="{'show': item.checkbox}"></i>{{ j }}
                      </div>
                      <!-- {{ item.values }} -->
                    </div>
                  </el-col>
                  <el-col :span="2">
                    <div class="grid-content bg-kw-light">
                      <span class="more-btn cursor" @click="handleViewMore(i)">
                        {{ item.open ? '收起' : '更多' }}
                        <img v-if="!item.open" src="../../assets/images/search/search_03.png"/>
                        <img v-else src="../../assets/images/search/search_14.png"/>
                      </span>
                    </div>
                  </el-col>

                </el-col>
              </el-row>
            </div>

            <div class="more-options" v-if="attributeList && attributeList.length>5" @click="handleShowMore()">
              {{ hideMore ? '更多选项' : '收起' }}
              <img v-if="hideMore" src="../../assets/images/search/search_03.png">
              <img v-else src="../../assets/images/search/search_14.png">
            </div>
          </div>
        </div>
      </div>

      <div class="search-bar">
        <div class="search-options-ul">
          <div :class="sortByActive == 0?'search-ops-li search-ops-li-active':'search-ops-li'" @click="sortTab(0)">
            综合排序
          </div>
          <div :class="sortByActive == 1?'search-ops-li search-ops-li-active':'search-ops-li'" @click="sortTab(1)">销量
            <!-- <img src="../../assets/images/search/search_15.png"> -->
            <img v-if="sortByActive == 1" src="../../assets/images/search/search_19.png">
            <img v-else src="../../assets/images/search/search_05.png">
          </div>
          <div :class="sortByActive == 2?'search-ops-li search-ops-li-active':'search-ops-li'" @click="sortTab(2)">新款
          </div>
          <div :class="sortByActive == 3?'search-ops-li search-ops-li-active':'search-ops-li'"
               @click="sortByPrice();sortTab(3)">
            价格
            <div :class="'triangle-icon '+ triangleStatus">
              <div class="triangle triangle-up"></div>
              <div class="triangle triangle-bottom"></div>
            </div>
          </div>
          <div :class="activePrice?'search-ops-li price-area out': 'search-ops-li price-area'">
            <div class="shadow">
              ￥<input class="search_input" v-model="listQuery.minPrice" :min="0" type="number" placeholder="最低价">
              - <input class="search_input" v-model="listQuery.maxPrice" :min="0" type="number" placeholder="最高价">
              <span class="confirm-btn" @click="getList()">确定</span>
            </div>

          </div>
          <!--<div class="search-ops-li">
            <el-select v-model="value1" filterable placeholder="货源地">
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </div>-->
          <div class="search-ops-li">
          </div>
          <!-- 隐藏认证商家 -->
          <!-- <div class="search-ops-li" @click="getListByCert">
            <el-checkbox v-model="checked" >认证商家</el-checkbox>
          </div> -->
        </div>
      </div>

      <div :class="productList && productList.length == 0?'search-products min-height-300':'search-products bg-white min-height-300'" v-loading="loading">
        <div class="search-pd-content">
          <div class="search-list" v-for="(item,index) in productList" :key="index">
            <img class="search-pd-img" v-if="item.mallType == 1" :src="URL.PIC+item.productImg "
             @click="goWebsite(item.mallType, item.productId, 'p')" :alt="item.productTitle">
             <img class="search-pd-img" v-if="item.mallType == 2" :src="item.productImg "
              @click="goWebsite(item.mallType, item.productId, 'p')" :alt="item.productTitle">
            <p class="search-pd-title" @click="goWebsite(item.mallType, item.productId, 'p')">
              {{ item.productTitle }}
            </p>
            <div class="search-price">￥{{ item.productPrice }}</div>
            <div class="search-pd-store" @click="goWebsite(item.mallType, item.factoryId, 'c', item.domainName)">{{ item.address }}</div>
            <div class="search-label">
              <img v-if="item.factoryType == 0 && item.mallType == 1" src="../../assets/images/search/search_08.png"/>
              <img v-else-if="item.factoryType == 1 && item.mallType == 1" src="../../assets/images/search/search_07.png"/>
              <img v-else-if="item.factoryType == 2 && item.mallType == 1" src="../../assets/images/search/search_09.png"/>
              <img class="switch-label" v-if="item.mallType == 1" src="../../assets/images/search/search_20.png" title="交易安全认证">
              <img class="switch-label" v-if="item.mallType == 2" src="../../assets/images/search/search_21.png" title="推广版">

            </div>
          </div>
        </div>

        <div v-if="productList && productList.length == 0">
          <div class="search-null">
            <img src="../../assets/images/member/notnull.png" class="search-nullImg">
            <p class="search-null-text">暂无内容哦~</p>
          </div>
        </div>
      </div>
      <Pagination v-show="total>0" :total="total" :page.sync="page" :limit.sync="size"
                  @pagination="getList"/>
    </div>
    <LikeItem/>
    <Footbars/>
  </div>
</template>
<script>
  import Headbar from '@/components/Layouts/Headbar'
  import HeadMenu from '@/components/Layouts/HeadMenu'
  import Hungbar from '@/components/Layouts/Hungbar'
  import Footbars from '@/components/Layouts/Footbars'
  import Pagination from '@/components/Pagination'
  import LikeItem from '@/components/Business/LikeItem'
  import {productSearch, categoryList, suggestCategory, attributeList } from '@/api/search'
  import { getCategoryFamily } from '@/api/product'

  export default {
    name: 'SearchProduct',
    components: {
      Headbar,
      HeadMenu,
      Hungbar,
      Footbars,
      Pagination,
      LikeItem
    },
    data() {
      return {
        loading: false,
        // kw: null,
        brand: this.getUrlParams('brand'),
        total: 0,
        productList: null,
        page: 1,
        size: 100,
        defaultFirst: '请选择',
        firstTrades: null,
        defaultSecond: '请选择',
        secondTrades: null,
        thirdTrades: null,
        defaultThird: '请选择',
        first: null,
        second: null,
        third: null,
        checked: false,
        productName: null,
        attributeList: null,
        hideMore: true,
        triangleStatus: '',
        triangleNum: 0,
        sortByActive: 0,
        searchType: 0,
        listQuery: {
          field: null,
          order: null,
          maxPrice: null,
          minPrice: null,
          factoryCertified: null,
          productAttributes: [],
          productAttributesName: [],
          categoryIds: this.getUrlParams('categoryIds') ? this.getUrlParams('categoryIds').split(','):[],
          categoryNames: [],
        },
        dynamicTags: [],// 搜索标签栏
        hiddenAttributes: [], //隐藏的属性
        activePrice: false,
      }
    },
    head() {
      return {
        title: '一呼百应工业品直卖网_'+(this.kw != undefined ? this.kw : '')+''+(this.categoryNames != undefined ? this.categoryNames : '')+'货源/供应',
        meta: [
          { name: 'keywords', content: '一呼百应,工业品直卖网,'+(this.kw != undefined ? this.kw : '')+''+(this.categoryNames != undefined ? this.categoryNames : '')+','+(this.kw != undefined ? this.kw : '')+''+(this.categoryNames != undefined ? this.categoryNames : '')+'货源,'+(this.kw != undefined ? this.kw : '')+''+(this.categoryNames != undefined ? this.categoryNames : '')+'供应' }
        ]
      }
    },
    async asyncData ({ app, query }) {
    
     // let categoryNames = [];
     // categoryNames.push(unescape(query.categoryNames))
     // console.log(categoryNames)

     let categoryIds = ''
     if(query.categoryIds){
        categoryIds = query.categoryIds
     }
     if(query.classifyId){
        categoryIds = query.classifyId
     }


      const params = {
          kw: query.kw,
          "sort.field": null,
          "sort.order": null,
          "pageable.page": 1,
          "pageable.size": 100,
          maxPrice: null,
          minPrice: null,
          categoryIds: categoryIds,
          categoryNames: query.categoryNames,
          factoryCertified: null,
          productAttributes: [],
          productAttributesName: [],
          brand: query.brand
        };
      let [res1] = await Promise.all([
       app.$axios.get('/search/product/search/merge', { params: params })
     ])

      // console.log(params)

     return{
      kw: query.kw,
      categoryNames: query.categoryNames,
      productList: res1.data.data.list,
      total: res1.data.data.pageCount
     }
    },
    beforeRouteLeave(to, from, next) {
      this.routeToPath(to.fullPath, 'new')
    },
    created() {
      if(this.getUrlParams('kw')){
        this.kw = unescape(decodeURI(this.$route.fullPath)).replace('/search/product?kw=', '');
      }else if(this.getUrlParams('brand')){
        this.brand = unescape(decodeURI(this.$route.fullPath)).replace('/search/product?brand=', '');
      }else if(this.getUrlParams('categoryNames')) {
        this.listQuery.categoryNames.push(unescape(this.getUrlParams('categoryNames')));
      }


      let classifyId = this.getUrlParams('classifyId');
      this.getSearchTradeNames(classifyId)
      this.listQuery.categoryIds.push(classifyId);
      this.getCommonAttributes();
     // this.getList();
      // this.getAttributeList('1097538801552723968');
    },
    methods: {
      getList() {
        const params = {
          kw: this.kw,
          "sort.field": this.listQuery.field,
          "sort.order": this.listQuery.order,
          "pageable.page": this.page,
          "pageable.size": this.size,
          maxPrice: this.listQuery.maxPrice,
          minPrice: this.listQuery.minPrice,
          categoryIds: this.listQuery.categoryIds.join(','),
          categoryNames: this.listQuery.categoryNames.join(','),
          factoryCertified: this.listQuery.factoryCertified,
          productAttributes: this.listQuery.productAttributes.join(','),
          productAttributesName: this.listQuery.productAttributesName.join(','),
          brand:this.brand
        };
        console.log(params)
        this.loading = true;
        productSearch(params).then(res => {
          this.loading = false
          this.total = res.data.pageCount;
          this.productList = res.data.list;

        });
      },
      //查看更多选项
      handleShowMore() {
        this.hideMore = !this.hideMore;
      },
      //获取通用属性
      getCommonAttributes() {
        if(this.kw){
          suggestCategory({keyWord: this.kw}).then(res=>{
            if (res.data && res.data.id) {
              attributeList({categoryId: res.data.id}).then(res => {
                this.attributeList = res.data;
              })
            }
          });
        }

        categoryList({tradeId: 0}).then(res => {
          this.firstTrades = res.data;
        });
      },
      //一级类目改变
      changeFirstTrade(tradeId) {
        this.thirdTrades=null;
        categoryList({tradeId: tradeId}).then(res => {
          this.second = null;
          this.secondTrades = res.data;
        });
        this.firstTrades.forEach(first =>{
          if (first.tradeId == tradeId) {
            this.listQuery.categoryIds= [];
            this.listQuery.categoryIds.push(first.id);
            this.listQuery.categoryNames= [];
            this.listQuery.categoryNames.push(first.tradeName);

            this.listQuery.kw = null;
            this.attributeList= null;
            this.getList();
          }
        });
      },
      //二级类目改变
      changeSecondTrade(tradeId) {
        this.thirdTrades = null;
        this.third = null;
        this.secondTrades.forEach(trade => {
          if (trade.tradeId == tradeId) {
            this.listQuery.categoryIds= [];
            this.listQuery.categoryIds.push(trade.id);
            this.listQuery.categoryNames= [];
            console.log(trade.tradeName)
            this.listQuery.categoryNames.push(trade.tradeName);
            this.listQuery.kw = null;
            this.attributeList= null;
            this.getList();
            if(trade.leaf) {
              this.getAttributeList(trade.id);
            }else {
              categoryList({tradeId: tradeId}).then(res => {
                this.thirdTrades = res.data;
              });
            }
          }
        });
      },
      //三级类目改变
      changeThirdTrade(id) {
        this.thirdTrades.forEach(trade => {
          if (trade.id == id) {
            this.listQuery.categoryNames = [];
            this.listQuery.categoryNames.push(trade.tradeName);
          }
        });
        this.listQuery.categoryIds= [];
        this.listQuery.categoryIds.push(id);

        this.listQuery.kw = null;
        this.getList();
        this.getAttributeList(id);
      },
      //根据子节点获取属性
      getAttributeList(id) {
        this.dynamicTags = [];
        //在标签栏显示的本项属相此栏隐藏
        this.hiddenAttributes = [];
        attributeList({categoryId: id}).then(res => {
          this.attributeList = res.data;
        })
      },
      //展开更多
      handleViewMore(i) {
        this.setItemTrue(i, 'open')
      },
      selectList() {
        if (this.productName && this.productName != '') {
          this.listQuery.categoryIds = this.third;
          this.kw = this.productName;
          this.getList();
        }
      },
      setItemTrue(index, name) {
        let item = this.attributeList[index]
        if (item[name] == undefined || !item[name]) {
          this.$set(item, [name], true)
        } else {
          this.$set(item, [name], false)
        }
      },
      // 搜索价格
      sortByPrice() {
        this.triangleNum++;
        if (this.triangleNum === 1) {
          this.triangleStatus = 'bottom';
          this.listQuery.field = 'product_price';
          this.listQuery.order = 'ASC';
        } else if (this.triangleNum === 2) {
          this.triangleStatus = 'up';
          this.listQuery.field = 'product_price';
          this.listQuery.order = 'DESC';
        }
        if (this.triangleNum === 3) {
          this.triangleNum = 0;
          this.triangleStatus = '';
          this.listQuery.field = null;
          this.listQuery.order = null;
        }
        this.getList();
      },
      //搜索
      sortTab(index) {
        if (this.sortByActive === index) {
          return false;
        }
        this.sortByActive = index;
        if (this.sortByActive !== 3) {
          if (this.sortByActive === 0) {
            this.listQuery.field = null;
            this.listQuery.order = null;
          } else if (this.sortByActive === 1) {
            this.listQuery.field = 'product_sale';
            this.listQuery.order = 'DESC';
          } else if (this.sortByActive === 2) {
            this.listQuery.field = 'publish_time';
            this.listQuery.order = 'DESC';
          }
          this.getList();
        }
      },
      handleClose(index, key) {
        this.hiddenAttributes.splice(this.hiddenAttributes.indexOf(index), 1);
        for (var i=0; i<this.dynamicTags.length; i++) {
          if (this.dynamicTags[i].index === index){
            this.dynamicTags.splice(i, 1);
            i = i - 1;
          }
        }
        this.listQuery.productAttributes.splice(this.listQuery.productAttributes.indexOf(key), 1);
        this.listQuery.productAttributesName.splice(this.listQuery.productAttributesName.indexOf(key), 1);

        this.getList();
      },
      //点击属性值搜索
      chooseAttribute(index, key, value, item) {
        //属性在标签栏显示
        this.dynamicTags.push({index: index, key: key, value: value});
        //在标签栏显示的本项属相此栏隐藏
        this.hiddenAttributes.push(index);

        this.listQuery.productAttributes.push(key);
        this.listQuery.productAttributesName.push(item.name+'_'+value);
        this.getList();
      },
      getListByCert(){
        this.listQuery.factoryCertified = this.checked? null: 1;
        this.getList();
      },
      //所有结果
      getAllResult(){
        //点击所有结果，防止重复访问接口
        if (this.searchType === 1) {
          return;
        }
        this.searchType = 1;
        this.listQuery = {
          field: null,
          order: null,
          maxPrice: null,
          minPrice: null,
          factoryCertified: null,
          productAttributes: [],
          productAttributesName: [],
          categoryIds: []
        };
        this.first = null;
        this.thirdTrades = null;
        this.secondTrades = null;
        this.getList();
      },
      //类目搜索时，把类目带入到下拉框里边
      getSearchTradeNames(val){
        if (val != null && val != '') {
          getCategoryFamily({id: val}).then(res=>{
            if (res && res.data.firstTradeId != null) {
              categoryList({tradeId: res.data.firstTradeId}).then(res1 => {
                this.firstTrades = res1.data;
              });
              this.first = res.data.firstTradeName;
            }
            if (res && res.data.secondTradeId!= null){
              categoryList({tradeId: res.data.secondTradeId}).then(res2 => {
                this.secondTrades = res2.data;
              });
              this.second = res.data.secondTradeName;
            }
            if (res && res.data.thirdTradeId!= null) {
              categoryList({tradeId: res.data.thirdTradeId}).then(res3 => {
                this.thirdTrades = res3.data;
              });
              this.third = res.data.thirdTradeName;
            }

          });
        }
      }
    }
  }
</script>
<style lang="scss" scoped>
  @import '@/styles/pages/search.scss';
  .confirm-btn{display: none;}
  .price-area:hover{
    .shadow{
      position: relative;
      margin-left: -10px;
      margin-right: -70px;
      padding-left: 10px;
      width: 400px;
      -webkit-box-shadow: 1px 1px 6px #aaa;
      box-shadow: 1px 1px 6px #aaa;
      background: #fff;
      z-index: 10;
      .confirm-btn{
        display: inline-block;
        margin-left: 5px;
        padding: 0 15px;
        line-height: 32px;
        border-radius: 3px;
        background: #255B8B;
        color: #fff;
      }
    }
  }

  .el-tag {
    margin-left: 10px;
  }

  .search-classify-row {
    background: #eee;
    &.hide {
      display: none;
    }
  }

  .grid-right {
    height: 36px;
    overflow: hidden;
    background: #fff;
  }

  .grid-right.more {
    height: auto;
  }

  .grid-right .checkbox {
    display: none;
    vertical-align: top;
    margin: 12px 4px 0 0;
    width: 10px;
    height: 10px;
    border: 1px solid #aaa;
    &.show {
      display: inline-block;
    }
  }

  .classify-kw.active {
    color: red;
    .checkbox {
      border-color: red;
    }
  }

  .grid-btn {
    overflow: hidden;
    width: 100%;
    text-align: center;
    padding-bottom: 20px;
    a {
      display: inline-block;
      vertical-align: top;
      width: 120px;
      height: 40px;
      line-height: 40px;
      text-align: center;
      margin: 0 20px;
      color: #fff;
      background: red;
    }
  }
</style>
<style lang="scss">
.search-main{
  .el-breadcrumb__inner{
    .el-input__inner {
      // background: #eee;
      // border: none;
      color: #888;
      background:rgba(250,250,250,1);
      border:1px solid rgba(221,221,221,1);
      border-radius: 0;
      background: #fafafa;
    }
  }


    .el-checkbox{
      color: #888;
    }
    .el-input__inner::-webkit-input-placeholder {
      color: #888;
    }
    .el-breadcrumb__inner{
      .el-select{
        min-width: 100px;
        width: 144px;
      }
    }
    .el-select .el-input__inner:focus {
      // border: none;
      border:1px solid rgba(221,221,221,1);
    }

    .el-select .el-input.is-focus .el-input__inner {
      // background: #eee;
      // border: none;
      background:rgba(250,250,250,1);
      border:1px solid rgba(221,221,221,1);
    }

    .el-checkbox__input.is-checked .el-checkbox__inner, .el-checkbox__input.is-indeterminate .el-checkbox__inner {
      background-color: #255b8b;
      border-color: #255b8b;
    }

    .el-checkbox__input.is-checked + .el-checkbox__label {
      color: #888;
    }

    .el-checkbox__inner:hover {
      // border-color: #888;
    }

    .el-checkbox__input.is-focus .el-checkbox__inner {
      // border-color: #888;
    }

  .search-conditions{
    .el-icon-arrow-right{
      margin-left: 10px;
      color: #ddd;
    }
    .el-breadcrumb__separator{
      margin: 0;
      margin-left: 10px;
    }
    .el-select{
      .el-input__inner{
        height: 32px;
        line-height: 32px;
        font-size: 12px;
      }
      .el-input__icon{
        line-height: 32px;
      }
    }
  }
}

</style>
